package dingtalk

import (
	"fmt"
	"net/url"
	"strconv"
	"time"
)

type DingTalk struct {
	accessToken string
	secret      string
}

func InitDingTalk(accessToken string, secret string) *DingTalk {
	return &DingTalk{accessToken: accessToken, secret: secret}
}

// Send 发送钉钉自定义机器人消息
// 消息发送频率限制
// 每个机器人每分钟最多发送20条消息到群里，如果超过20条，会限流10分钟
func (d *DingTalk) Send(msg *Message) error {
	u := sendURL + url.QueryEscape(d.accessToken)
	if d.secret != "" {
		timestamp := strconv.FormatInt(time.Now().UnixMilli(), 10)
		sign, err := Sign(timestamp, d.secret)
		if err != nil {
			return fmt.Errorf("sign failed: %w", err)
		}
		u = u + "&timestamp=" + timestamp + "&sign=" + url.QueryEscape(sign)
	}
	var resp ResponseMeta
	_, err := postJSON(u, msg, &resp)
	if err != nil {
		return err
	}
	if !resp.Succeed() {
		return fmt.Errorf("%w; %v", ErrRequest, resp)
	}
	return nil
}
